package com.evry.spring3sandbox.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.evry.spring3sandbox.service.ProductManager;

@Controller
public class ProductDetailsController {

	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private ProductManager productManager;

	@RequestMapping(value = "/products/{id}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("id") int id, Model model) {
		if(id == 0){
			return "redirect:/";
		}
		if(id-1 < productManager.getProducts().size()){
			model.addAttribute("product", productManager.getProducts().get(id-1));
		}else{
			logger.info("No product with id " + id + " found. Redirecting back to inventory page.");
			return "redirect:/";
		}
		return "products";
	}
}
